package com.icongyou.enterprise.talent_pool.service.impl;

import com.icongyou.enterprise.talent_pool.entity.vo.AssignmentPerformanceVO;
import com.icongyou.enterprise.talent_pool.entity.vo.AssignmentTagVO;
import com.icongyou.enterprise.talent_pool.mapper.TagMapper;
import com.icongyou.enterprise.talent_pool.service.AIModelService;
import com.icongyou.enterprise.talent_pool.service.CoreCompetenceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class CoreCompetenceServiceImpl implements CoreCompetenceService {

    private final AIModelService aiModelService;
    private final TagMapper tagMapper;

    /**
     * 基于已有数据生成学生核心竞争力标签（更高效的方案）
     */
    @Override
    public String generateCoreCompetenceLabel(String demandText,
                                              String studentId,
                                              List<AssignmentTagVO> relevantAssignments,
                                              List<AssignmentPerformanceVO> studentPerformances) {

        try {
            // 构建提示词，直接使用已有的任务-标签关联和学生表现数据
            String prompt = buildCoreCompetencePromptFromExistingData(demandText, studentId,
                    relevantAssignments, studentPerformances);
            Map<String, Object> request = aiModelService.buildAIModelRequest(prompt);

            // 调用大模型
            Map<String, Object> response = aiModelService.callAIModelAPI(request);
            return parseCoreCompetenceResponse(response);

        } catch (Exception e) {
            return getFallbackCoreCompetenceLabel();
        }
    }

    /**
     * 基于已有数据构建核心竞争力提示词
     */
    private String buildCoreCompetencePromptFromExistingData(String demandText,
                                                             String studentId,
                                                             List<AssignmentTagVO> relevantAssignments,
                                                             List<AssignmentPerformanceVO> studentPerformances) {
        StringBuilder prompt = new StringBuilder();

        prompt.append("你是一个人才评估专家，请根据企业需求和学生在相关技术任务上的表现数据，为该学生生成一段简短的核心竞争力标签（不超过13个字）。\n\n");

        if (demandText != null && !demandText.trim().isEmpty()) {
            prompt.append("企业需求：").append(demandText).append("\n\n");
        }

        prompt.append("学生在相关技术任务上的表现：\n");

        // 构建任务表现映射，便于查找
        Map<String, AssignmentPerformanceVO> performanceMap = studentPerformances.stream()
                .collect(Collectors.toMap(AssignmentPerformanceVO::getAssignmentId, p -> p));

        // 按关联度排序，展示最重要的任务
        List<AssignmentTagVO> sortedAssignments = relevantAssignments.stream()
                .sorted((a, b) -> b.getRelevance().compareTo(a.getRelevance()))
                .limit(5) // 只取前5个最相关的任务
                .collect(Collectors.toList());

        for (AssignmentTagVO assignment : sortedAssignments) {
            AssignmentPerformanceVO performance = performanceMap.get(assignment.getAssignmentId());

            prompt.append("- 任务：").append(assignment.getAssignmentName()).append("\n");
            prompt.append("与需求标签").append(tagMapper.getTagNameById(assignment.getTagId())).append("相关\n");
            prompt.append("  关联度为：").append(String.format("%.2f", assignment.getRelevance())).append("\n");
            prompt.append("  任务权重为：").append(String.format("%.2f", assignment.getAssignmentWeight())).append("\n");

            if (performance != null) {
                double normalizedScore = performance.getPerformanceScore().doubleValue() / 100.0;
                prompt.append("  学生在该任务表现得分：").append(String.format("%.1f", performance.getPerformanceScore()))
                        .append(" (归一化：").append(String.format("%.2f", normalizedScore)).append(")\n");
            } else {
                prompt.append("  学生在该任务表现得分：暂无数据\n");
            }
            prompt.append("\n");
        }

        prompt.append("请综合分析以上数据，生成一段简短的核心竞争力标签，突出学生在相关技术领域的优势，要求13个字以内\n");
        prompt.append("示例1：\"前端能力突出，熟悉测试\"\n");
        prompt.append("示例2：\"擅长Java开发\"\n");
        prompt.append("请直接返回描述文本，不要包含任何其他内容。");

        return prompt.toString();
    }

    /**
     * 解析核心竞争力响应（保持不变）
     */
    @SuppressWarnings("unchecked")
    public String parseCoreCompetenceResponse(Map<String, Object> response) {
        try {
            Map<String, Object> output = (Map<String, Object>) response.get("output");
            if (output != null) {
                String content = (String) output.get("text");
                if (content != null && !content.trim().isEmpty()) {
                    // 清理可能的额外文本
                    String cleaned = content.trim()
                            .replaceAll("^\"|\"$", "") // 移除首尾引号
                            .replaceAll("^'|'$", "")   // 移除首尾单引号
                            .trim();
                    return cleaned;
                }
            }
            return getFallbackCoreCompetenceLabel();
        } catch (Exception e) {
            return getFallbackCoreCompetenceLabel();
        }
    }

    /**
     * 核心竞争力标签的降级方案
     */
    public String getFallbackCoreCompetenceLabel() {
        String[] fallbackLabels = {
                "技术基础扎实，学习能力强",
                "具备良好的编程能力和问题解决能力",
                "专业知识掌握牢固，实践能力良好",
                "综合能力均衡，发展潜力大",
                "技术理解深入，应用能力突出"
        };
        return fallbackLabels[new Random().nextInt(fallbackLabels.length)];
    }
}